package com.huobao.yunying.activitys.muyingquan;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ViewInject;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huobao.yunying.adapters.Adapter_Host_Tiezi;
import com.huobao.yunying.base.HuobaoBaseActivity;
import com.huobao.yunying.fragments.Fragment_MuyingQuan;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.utils.ImageUtils;
import com.huobao.yunying.utils.ImageUtils.OnImageLoadListener;
import com.huobao.zhangying.R;
import com.xrz.sxm.base.utils.ExitUtil;
import com.xrz.sxm.base.utils.ScreenUtil;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 母婴圈
 * 
 * @author Administrator
 *
 */
public class Act_Muyingquan extends HuobaoBaseActivity implements OnScrollListener,OnClickListener,OnItemClickListener {
	// 顶部4个图片
	private ImageView img_1;
	private ImageView img_2;
	private ImageView img_3;
	private ImageView img_4;

	private TextView tv_1;
	private TextView tv_2;
	private TextView tv_3;
	private TextView tv_4;

	private LinearLayout llyt_1;
	private LinearLayout llyt_2;
	private LinearLayout llyt_3;
	private LinearLayout llyt_4;
	
	private LinearLayout llyt;
	////// 结束

	// 当前页数
	private int m_CurrentPage = 1;

	@ViewInject(R.id.listview)
	private ListView listview;

	private Adapter_Host_Tiezi adapter;

	private TextView tv_FootMsg;
	private boolean isLoading = true;
	
	private List<Muyingquan_FristTop> m_List;

	@Override
	protected int getContentView() {
		return R.layout.layout_act_muyngquan;
	}

	@Override
	protected String getTitleText() {
		return null;
	}

	@Override
	protected void init() {
		EventBus.getDefault().register(this);
		mAbTitleBar.setVisibility(View.GONE);
		View HeadView = LayoutInflater.from(context).inflate(R.layout.include_muying_headerview, null);
		initHeadView(HeadView);
		View footView = LayoutInflater.from(context).inflate(R.layout.item_footview, null);
		tv_FootMsg = (TextView) footView.findViewById(R.id.tv_message);
		adapter = new Adapter_Host_Tiezi(context);
		listview.setOnItemClickListener(this);
		listview.setOnScrollListener(this);
		listview.addHeaderView(HeadView,null,false);
		listview.addFooterView(footView,null,false);
		listview.setAdapter(adapter);
		getQuanzi();
	}

	private void initHeadView(View headView) {
		img_1 = (ImageView) headView.findViewById(R.id.img_1);
		img_2 = (ImageView) headView.findViewById(R.id.img_2);
		img_3 = (ImageView) headView.findViewById(R.id.img_3);
		img_4 = (ImageView) headView.findViewById(R.id.img_4);

		tv_1 = (TextView) headView.findViewById(R.id.tv_1);
		tv_2 = (TextView) headView.findViewById(R.id.tv_2);
		tv_3 = (TextView) headView.findViewById(R.id.tv_3);
		tv_4 = (TextView) headView.findViewById(R.id.tv_4);

		llyt_1 = (LinearLayout) headView.findViewById(R.id.llyt_1);
		llyt_2 = (LinearLayout) headView.findViewById(R.id.llyt_2);
		llyt_3 = (LinearLayout) headView.findViewById(R.id.llyt_3);
		llyt_4 = (LinearLayout) headView.findViewById(R.id.llyt_4);
		
		llyt  = (LinearLayout) headView.findViewById(R.id.llyt);
		
		llyt_1.setOnClickListener(this);
		llyt_2.setOnClickListener(this);
		llyt_3.setOnClickListener(this);
		llyt_4.setOnClickListener(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}

	@Subscriber(tag = "setUserVisibleHint")
	public void setUserVisibleHint(boolean isVisibleToUser) {
		if (isVisibleToUser)
			getList(true);
	}

	private void getList(boolean showDialog) {
		isLoading = true;
		Map<String, String> map = HttpUtil.getParams("app", "postbar", "act", "hotpost", "page", m_CurrentPage + "");
		Http.getInstant().sendRequest(context, showDialog, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				JSONArray array = jsonObject.getJSONArray("retval");
				List<FristHostTiezi> list = new ArrayList<FristHostTiezi>();
				for (int i = 0; i < array.size(); i++) {
					JSONObject object = array.getJSONObject(i);
					FristHostTiezi tiezi = JSON.parseObject(object.toString(), FristHostTiezi.class);
					List<String> images = JSON.parseArray(object.getString("images"), String.class);
					tiezi.setImages(images);
					list.add(tiezi);
				}
				if (list == null || list.size() == 0) {
					tv_FootMsg.setText("加载完成");
					isLoading = true;
					return;
				}
				adapter.addAll(list);
				isLoading = false;
			}

			@Override
			public void onHttpError(String error) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void getQuanzi() {
		Map<String, String> map = HttpUtil.getParams("app", "postbar", "act", "grouplist");
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				List<Muyingquan_FristTop> list = JSON.parseArray(jsonObject.getString("retval"),
						Muyingquan_FristTop.class);
				m_List = list;
				if (list != null && list.size() != 0) {
					checkVisi(list);
				}
			}

			private void checkVisi(List<Muyingquan_FristTop> list) {
				int size = list.size();
				if (size >= 4) {
					loadIcon(llyt_1,img_1, list.get(0).getAvatar());
					loadIcon(llyt_2,img_2, list.get(1).getAvatar());
					loadIcon(llyt_3,img_3, list.get(2).getAvatar());
					loadIcon(llyt_4,img_4, list.get(3).getAvatar());
					tv_1.setText(list.get(0).getGname());
					tv_2.setText(list.get(1).getGname());
					tv_3.setText(list.get(2).getGname());
					tv_4.setText(list.get(3).getGname());
				} else {
					switch (size) {
					case 1:
						loadIcon(llyt_1,img_1, list.get(0).getAvatar());
						tv_1.setText(list.get(0).getGname());
						llyt_2.setVisibility(View.INVISIBLE);
						llyt_3.setVisibility(View.INVISIBLE);
						llyt_4.setVisibility(View.INVISIBLE);
						break;
					case 2:
						loadIcon(llyt_1,img_1, list.get(0).getAvatar());
						loadIcon(llyt_2,img_2, list.get(1).getAvatar());
						tv_1.setText(list.get(0).getGname());
						tv_2.setText(list.get(1).getGname());
						llyt_3.setVisibility(View.INVISIBLE);
						llyt_4.setVisibility(View.INVISIBLE);
						break;
					case 3:
						loadIcon(llyt_1,img_1, list.get(0).getAvatar());
						loadIcon(llyt_2,img_2, list.get(1).getAvatar());
						loadIcon(llyt_3,img_3, list.get(2).getAvatar());
						tv_1.setText(list.get(0).getGname());
						tv_2.setText(list.get(1).getGname());
						tv_3.setText(list.get(2).getGname());
						llyt_4.setVisibility(View.INVISIBLE);
						break;
					}
				}

			}

			@Override
			public void onHttpError(String error) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void loadIcon(final LinearLayout layout,final ImageView image, String url) {
		ImageUtils.loadimg(image, url, new OnImageLoadListener() {

			@Override
			public void onLoadSuccess(Drawable drawable) {
				int oldWidth = drawable.getIntrinsicWidth();
				int oldHight = drawable.getIntrinsicHeight();
				int newWidth = ScreenUtil.getInstant().getDisWidth(context) / 4 - 100;
				int newHight = newWidth * oldHight / oldWidth;
				LayoutParams layoutParams = (LayoutParams) image.getLayoutParams();
				layoutParams.width = newWidth;
				layoutParams.height = newHight;
				layoutParams.gravity = Gravity.CENTER;
				image.setLayoutParams(layoutParams);
				
//				layoutParams = (LayoutParams) layout.getLayoutParams();
//				layoutParams.height = LayoutParams.WRAP_CONTENT;
//				layout.setLayoutParams(layoutParams);
//				
//				
//				layoutParams = (LayoutParams) llyt.getLayoutParams();
//				layoutParams.width = LayoutParams.WRAP_CONTENT;
//				layoutParams.height = LayoutParams.WRAP_CONTENT;
//				llyt.setLayoutParams(layoutParams);
			}
		});
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if ((firstVisibleItem + visibleItemCount) >= totalItemCount) {
			if (isLoading) {
				return;        
			}
			isLoading = true;
			m_CurrentPage++;
			getList(false);
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent(this, Act_Quanzi_Detail.class);
		switch(v.getId()){
		case R.id.llyt_1:
			intent.putExtra("id", m_List.get(0).getGid());
			break;
		case R.id.llyt_2:
			intent.putExtra("id", m_List.get(1).getGid());
			break;
		case R.id.llyt_3:
			intent.putExtra("id", m_List.get(2).getGid());
			break;
		case R.id.llyt_4:
			intent.putExtra("id", m_List.get(3).getGid());
			break;
		}
		startActivity(intent);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		LogUtil.e("position="+position);
		if(position == 0 || position == adapter.getCount())return;
		FristHostTiezi tiezi = adapter.getItem(position-1);
		Intent intent = new Intent(this, Act_Tiezi_Detail.class);
		intent.putExtra("quanziid", tiezi.getGid());
		intent.putExtra("id", tiezi.getPid());
		LogUtil.e("quanziid="+tiezi.getGid());
		LogUtil.e("id="+tiezi.getPid());
		startActivity(intent);
		
	}
	
	private long tempTime = 0;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(tempTime == 0){
				tempTime = System.currentTimeMillis();
				Toast.makeText(context, "再按一次退出程序!", Toast.LENGTH_SHORT).show();
				return false;
			}
			if((System.currentTimeMillis() - tempTime) <= 2 * 1000){
				//退出程序-
				ExitUtil.getInstant().exitApp(context);
				finish();
				return false;
			}
			Toast.makeText(context, "再按一次退出程序!", Toast.LENGTH_SHORT).show();
			tempTime = System.currentTimeMillis();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
}
